//
//  MainViewController.swift
//  DSWeibo
//
//  Created by silence on 16/1/26.
//  Copyright © 2016年 silence. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        /**
        添加所有子控件
        */
        addChildViewControllers()
       
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        // 此时tabbarButton都已经创建
        setupComposeBtn()
    }
    
    private func setupComposeBtn()
    {
        tabBar.addSubview(composeBtn)
        
        // 1.计算按钮的宽度
        let width = tabBar.bounds.width / CGFloat((viewControllers?.count)!)
        // 2.创建按钮frame
        let rect = CGRect(x: 0, y: 0, width: width, height: tabBar.bounds.height)
        
        // 3.设置按钮的frame和偏移量
        composeBtn.frame = CGRectOffset(rect, width*2, 0)
    }
    
    /**
     监听加号按钮点击
     注意：运行循环监听到事件后，向VC发送消息，动态执行方法，因此不能设置为private
     */
    func composeBtnClick() {
        print(__FUNCTION__)
    }
    
    
    
    /**
     添加所有子控制器
     */
    private func addChildViewControllers()
    {
        // 1.获取json文件路径
        let jsonPath = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil)
        // 2.加载json数据
        let jsonData = NSData(contentsOfFile: jsonPath!)
        
        // 3.序列化json
        do {
            
            let dictArray = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers)
            
            // 遍历字典时需要明确指明数组中的数据类型
            for dict in dictArray as! [[String:String]]
            {
                addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!)
            }
            
        } catch {
            
            print(error)

            addChildViewController("HomeTableViewController", title: "首页", imageName: "tabbar_home")
            addChildViewController("MessageTableViewController", title: "消息", imageName: "tabbar_message_center")
            // 添加一个占位控制器：给中间加号按钮挪位置
            addChildViewController("NullViewController", title: "", imageName: "")
            
            addChildViewController("DiscoverTableViewController", title: "广场", imageName: "tabbar_discover")
            addChildViewController("ProfileTableViewController", title: "我", imageName: "tabbar_profile")
        }
        
       
    }
    
    /**
    初始化自控制器
    
    - parameter childController: 需要初始化的自控制器
    - parameter title:           子控制器的标题
    - parameter imageName:       子控制器的图片
    */
    //    func addChildViewController(childController: UIViewController, title:String, imageName:String) {
    private func addChildViewController(childControllerName: String, title:String, imageName:String) {
        
        // 0.动态获取命名空间
        let namespace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
        //print(namespace) //DSWeibo
        
        // 告诉编译器暂时就是AnyClass
        let cls:AnyClass = NSClassFromString(namespace + "." + childControllerName)!
        print(cls) //HomeTableViewController
        
        // 告诉编译器真实类型是UIViewController
        let vcCls = cls as! UIViewController.Type
        
        let vc = vcCls.init()
        
        
        // 1.1设置首页tabbar对应的数据
        vc.tabBarItem.image = UIImage(named: imageName)
        vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted")
        vc.title = title
        
        // 2.给首页包装一个导航控制器
        let nav = UINavigationController()
        nav.addChildViewController(vc)
        
        // 3.将导航控制器添加到当前控制器上
        addChildViewController(nav)
        
    }
    
    
    //MARK: - 懒加载
    /// 中间加号按钮
    private lazy var composeBtn:UIButton = {
        
        // 1.创建按钮
        let button = UIButton()
        
        // 2.设置中间加好图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        // 3.设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        // 4.监听加好按钮点击
        button.addTarget(self , action: "composeBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 5.返回按钮
        return button
        
    }()
}
